﻿artApp.factory('LoginService', function ($q, $http, $window) {

    var login = function (username, password) {
        var deferred = $q.defer();
        $http({
            url: '/Token',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            method: 'POST',
            data: 'username=' + username + '&password=' + password + '&grant_type=password'
        }).success(function (data) {
            var token = data.access_token;
            $window.sessionStorage.setItem('token', token);
            deferred.resolve(data.userName);
        }).error(function (data) {
            deferred.reject(data);
        });

        return deferred.promise;
    }

    var isLoggedIn = function () {
        return $window.sessionStorage.getItem('token');
    }

    var logout = function () {
        $window.sessionStorage.removeItem('token');

        return true;
    }

    return {
        login: login,
        isLoggedIn: isLoggedIn,
        logout: logout
    }
});